import json, time, requests

def get_time_dif(start_time):
    end_time = time.time()
    time_dif = end_time - start_time 
    return time_dif     

def test_service(content, ip, port):
    url = f'http://{ip}:{port}/ExamServer'
    app_data = {"request_id": "ExamServer", "query": content}
    app_data = json.dumps(app_data).encode("utf-8")
    try:
        response = requests.post(url, app_data)
        response = json.loads(response.text)
    except Exception as e:
        print(e)
        response = None
    return response

def test_time(content, ip, port, num=100):
    assert num > 0
    time_usage = 0.0
    for i in range(num):
        start_time = time.time()
        test_service(content, ip, port)
        time_usage += get_time_dif(start_time)
    print("Time usage average is {:.4f} s.".format(time_usage / num))

if __name__=='__main__':
    ip, port = "0.0.0.0", 5950
    content = ["菠菜从土壤中吸收的氮元素可以用来合成（）A.淀粉和纤维素B.葡萄糖和DNAC.核酸和蛋白质D.麦芽糖和脂肪酸"]
    res = test_service(content, ip, port)
    print(res)
    test_time(content, ip, port, num=100)
